<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top" label-width="100px" class="broadcast-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="标题" prop="title">
            <el-input v-model="postForm.title" />
            <div class="form-tips text-warning">扫码后微信图文的标题</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="meetingList.length > 0" :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="所属会议" prop="meetingName">
            <ul class="link-list">
              <li
                v-for="item in meetingList"
                :key="item.id"
              >
                <router-link
                  :to="`/meetings/list/${item.id}?type=invite`"
                >{{ item.meetingtitle }}</router-link>
              </li>
            </ul>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="直播平台" prop="platformId">
            <el-select
              v-model="postForm.platformId"
              filterable
              clearable
              placeholder="请选择直播平台"
              style="width:100%"
            >
              <el-option
                v-for="item in platformOptions"
                :key="item.id"
                :label="item.platformName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="频道ID" prop="channeId">
            <el-input v-model="postForm.channeId" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="直播地址" prop="broadcastUrl">
            <el-input v-model="postForm.broadcastUrl" />
            <div class="form-tips text-warning">以 http:// 或 https:// 开始</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="15" :offset="3">
          <el-form-item label="第三方跳转地址" prop="thirdPartyLink" :required="isRedirected">
            <el-input v-model="postForm.thirdPartyLink" />
            <div class="form-tips text-warning">以 http:// 或 https:// 开始</div>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="第三方跳转" prop="isRedirect" class="text-center">
            <el-switch v-model="postForm.isRedirect" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="封面" prop="cover">
            <el-upload
              v-if="coverList < 1"
              :action="uploadUrl"
              :multiple="false"
              :limit="1"
              name="fies"
              :headers="{token}"
              :on-success="handleUploadSucc"
              :show-file-list="false"
              drag
              accept="image/jpeg,image/png,image/gif"
              class="drag-upload-wrapper"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>

            <ul v-else class="thumb-img-list">
              <li
                v-for="(item, index) in coverList"
                :key="index"
                class="item"
              >
                <img :src="item.url" :alt="item.name" class="img">
                <div
                  class="el-icon-close close-btn"
                  title="点击可删除"
                  @click="handleUploadRemove(item)"
                />
              </li>
            </ul>
            <div class="form-tips text-warning">扫码后微信图文的封面，建议尺寸：750x320，或同比例尺寸</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="postForm.status"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3" :offset="3">
          <el-form-item label="是否上线" prop="isOnline" class="text-center">
            <el-switch v-model="postForm.isOnline" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getAllMeetingsList
} from '@/api/meetings'
import {
  liveBroadcastShow,
  addLiveBroadcast,
  editLiveBroadcast,
  getPlatformList
} from '@/api/liveBroadcasts'

const defaultForm = {
  id: undefined,
  title: '',
  // meetingId: '',
  meetingName: '',
  platformId: '',
  channeId: '',
  broadcastUrl: '',
  cover: '',
  status: 0,
  isOnline: 0,
  isRedirect: 0,
  thirdPartyLink: ''
}

export default {
  name: 'LiveBroadcastForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateThirdLink = (rule, value, callback) => {
      if (this.postForm.thirdPartyLink === '' && this.postForm.isRedirect === 1) {
        callback(new Error('请输入第三方跳转地址'))
      } else {
        callback()
      }
    }

    return {
      platformOptions: [],
      statusOptions: [
        {
          name: '未开始',
          id: 0
        },
        {
          name: '进行中',
          id: 1
        },
        {
          name: '已结束',
          id: 2
        }
      ],
      meetingsOptions: [],
      coverList: [],
      meetingList: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        title: [
          { required: true, message: '请输入直播标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        platformId: [
          { required: true, message: '请选择直播平台', trigger: 'change' }
        ],
        channeId: [
          { required: true, message: '请输入频道ID', trigger: 'blur' }
        ],
        broadcastUrl: [
          { required: true, message: '请输入直播地址', trigger: 'blur' }
        ],
        thirdPartyLink: [
          { validator: validateThirdLink }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/content/imgUpload'
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ]),
    isRedirected() {
      return this.postForm.isRedirect === 1
    }
  },
  created() {
    this.fetchMeetingsList()
    this.fetchPlatform()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchPlatform() {
      getPlatformList().then(response => {
        // console.log(response)
        this.platformOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchMeetingsList() {
      getAllMeetingsList().then(response => {
        // console.log(response)
        this.meetingsOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      liveBroadcastShow({ id }).then(response => {
        const { data } = response
        // console.log(data)
        this.coverList = []
        if (!this._.isEmpty(data.cover)) {
          this.coverList.push({
            name: 'uploadCover' + 0,
            url: data.cover
          })
        }
        this.postForm.id = data.id
        this.postForm.title = data.title
        this.meetingList = data.meetingList
        // this.postForm.meetingId = data.meetingId
        this.postForm.meetingName = data.meetingName
        this.postForm.platformId = data.platformId
        this.postForm.channeId = data.channeId
        this.postForm.broadcastUrl = data.broadcastUrl
        this.postForm.cover = data.cover
        this.postForm.status = data.status
        this.postForm.isOnline = data.isOnline
        this.postForm.isRedirect = data.isRedirect
        this.postForm.thirdPartyLink = data.thirdPartyLink
        // console.log(this.coverList)
      }).catch(err => {
        console.log(err)
      })
    },
    // changeMeeting(meetingId) {
    //   let meetingObj = {}
    //   meetingObj = this.meetingsOptions.find((item) => {
    //     return item.id === meetingId
    //   })
    //   this.postForm.meetingName = meetingObj.meetingtitle
    // },
    handleUploadRemove(file) {
      // console.log(file)
      const index = this.coverList.indexOf(file)
      if (index !== -1) {
        this.coverList.splice(index, 1)
        this.postForm.cover = ''
      }
    },
    handleUploadSucc(res) {
      // console.log(res)
      res.data.forEach((item, index) => {
        if (this.coverList.indexOf(item) === -1) {
          this.postForm.cover = item
          this.coverList.push({
            name: 'uploadCover' + index,
            url: item
          })
        }
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            editLiveBroadcast(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑直播成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addLiveBroadcast(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加直播成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .broadcast-form {
    padding: 40px 140px;
  }
}
</style>
